<template>
	<view @click.once="pushState" class="form-box" >
		<m-progress :percent="percent"  />
		<view class="estimate-amount-box">
			<view class="left">
				<view class="value">
					{{20000+expectAmount}}
				</view>
				<view class="label">
					预估额度（元）
				</view>
			</view>
			<view v-if="!isQuestionEnd" class="right">
				<text>{{currentIndex+1}}</text>/{{danxuanBtn.length}}
			</view>
		</view>
		<view class="tips">
			温馨提示：请填写正确信息，以免影响额度
		</view>
		<userInfo v-if="isQuestionEnd" @submit="postInfo($event)" />
		<selectQuestion v-else @change="questionChange"  :data="danxuanBtn" />
		
		</view>
	
	<!-- 返回监听 -->
	<mpopum title='即将完成申请' ref="backPopupRef" confirmText="继续申请" >
		<div style="height: 4em;">
			仅需1分钟就可完成申请啦，让我们继续申请吧！
		</div>
	</mpopum>
	 <protocol ref="protocolRef"> </protocol>
</template>

<script>
	import pickers from "@/components/ming-picker/ming-picker.vue"
	import axbCheckBox from '@/components/axb-checkbox/axb-checkbox.vue'
	import MbuttomVue from "@/components/Mbuttom.vue"
	import qs from 'qs'
	import mpopum from '@/components/mPopup.vue'
	import protocol from "./modules/protocol.vue"
	import handleData from "./modules/handleData"
	import selectQuestion from './modules/select-question.vue'
	import mProgress from "./modules/progress.vue"
	import userInfo from './modules/userInfo.vue'
	export default {
		data() {
			return {
				currentIndex:0,
				expectAmount:0,
				percent:50,
				isQuestionEnd:false,
				danxuanBtn: [],
				assets: [],
				username: '',
				idCard: '',
				loanAmount: '',
				zhimafenValue: '',
				width: 0,
				height: 0,
				addressTitle: '请选择城市',
				chooseAssets: false,
				provinceCode: '',
				cityCode: '',
			}
		},
	
		onUnload() {
			window.onpopstate = null
		},
		onHide() {
			window.onpopstate = null
		},
		onLoad() {
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight
			
			addEventListener('resize', () => {
				// 键盘弹出的时候内容往上推
				uni.pageScrollTo({
					scrollTop:10000
				})
			})
			// #ifdef H5
			window.onpopstate = () => {
					// mPopupRef.value.getPopup().close()
					this.$refs.backPopupRef.getPopup().open()
			}
			const getLocalAddress = () => {
				const mapObj = new AMap.Map('iCenter');
				mapObj.plugin('AMap.Geolocation', () => {
					const geolocation = new AMap.Geolocation({
						enableHighAccuracy: true, //是否使用高精度定位，默认:true
						GeoLocationFirst: true,
						timeout: 10000, //超过10秒后停止定位，默认：无穷大
						maximumAge: 0, //定位结果缓存0毫秒，默认：0
						convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
					});
					mapObj.addControl(geolocation);
					geolocation.getCurrentPosition();
					AMap.event.addListener(geolocation, 'complete', (res) => {
						const {
							lat,
							lng
						} = res.position
						const geocoder = new AMap.Geocoder({
							radius: 1000 //范围，默认：500
						});
						console.log('获取经纬度---', [lng, lat])
						geocoder.getAddress([lng, lat], (status, result) => {
							if (status === 'complete' && result.regeocode) {
								const address = result.regeocode.formattedAddress;
								console.log(address, result.regeocode)
								const {
									adcode,
									province,
									city,
									district
								} = result.regeocode.addressComponent
								const addressList = [province, city, district]
								if (this.addressTitle === '请选择城市') {
									this.addressTitle = addressList.filter(item => !!item).join('-')
									this.provinceCode = (adcode && adcode.length >= 2) ? adcode.slice(0, 2) : '';
									this.cityCode = (adcode && adcode.length >= 4) ? adcode.slice(0, 4) : '';
								}
								console.log(addressList, this.provinceCode, this.cityCode)
							} else {
								console.error('根据经纬度查询地址失败')
							}
						});
					}); //返回定位信息
					AMap.event.addListener(geolocation, 'error', () => {
						console.log('获取位置失败')
					}); //返回定位出错信息
				});

			}
			if (window.AMap && window.AMap.Geocoder) {
				getLocalAddress()
			} else {
				const scriptDom = document.createElement('script')
				scriptDom.src = 'https://webapi.amap.com/maps?v=1.4.15&key=bd71492679f83a2214787eaeda4891ba&plugin=AMap.Geocoder'
				scriptDom.onload = () => {
					getLocalAddress()
				}
				document.querySelector('head').append(scriptDom)
			}

			// #endif

			this.getInfo()

		},
		onReady() {
			let systemInfo = uni.getSystemInfoSync()
			this.width = systemInfo.windowWidth
			this.height = systemInfo.windowHeight
		},

		methods: {
			questionChange(e){
				this.expectAmount = e.amount
				this.isQuestionEnd = e.isEnd
				this.percent = e.percent
				if(e.isEnd){
				}else{
					this.currentIndex = e.index
				}
				
				
			},
			 pushState(){
				// #ifdef H5
				history.pushState({},'')
				// #endif
			},
			address(e) {
				this.addressTitle = e.value.join('-')

				this.provinceCode = e.code[0]
				this.cityCode = e.code[1]
			},
			async getInfo() {
				const res = await this.$myRequest({
					url: 'api/member/getBaseInfo',
					method: 'post',
					data: {
						
					}
				});
				handleData(res)
				this.danxuanBtn = res.multDataList
				this.assets = res.singleDataList
				console.log('res 过滤后',res)
				

			},
			//限制只能输入汉字
			onKeyNameInput: function(event) {
				var value = event.target.value;



				if (!value || value == " ") {
					return '';
				}
				const rule = /[^\u4E00-\u9FA5]/g;
				this.$nextTick(function() {

					this.username = value.replace(rule, '');
					// console.log(this.name)



				})

			},
			async postInfo(form) {
				let infoMap = {}
				console.log(form)
				Object.assign(infoMap, {
					'username': form.username
				})
				Object.assign(infoMap, {
					'idCard': form.idCard
				})

				// Object.assign(infoMap, {
				// 	'zhimaScore': form.zhimafenValue
				// })
				Object.assign(infoMap, {
					'address': form.addressTitle
				})
		
				console.log('this.danxuanBtn',this.danxuanBtn )
				this.danxuanBtn.forEach((item) => {
					if (typeof item.chooseIndex == 'number') {
						infoMap[item.value] = item.itemList[item.chooseIndex].value
					}
				})
			
				if (form.username == '' || form.idCard == '') {
					uni.showToast({
						title: '请完善身份信息',
						icon: 'error'
					})
					return;
				}
				if (form.idCard.length != 18) {
					uni.showToast({
						title: '请输入正确的身份证信息',
						icon: 'error'
					})
					return;
				}

				if (form.addressTitle == '请选择城市') {
					uni.showToast({
						title: '请选择城市',
						icon: 'error'
					})
					return;
				}
				
				Object.assign(infoMap, {
					'provinceCode': form.provinceCode
				})
				Object.assign(infoMap, {
					'cityCode': form.cityCode
				})
				const resGetUserInfo = await this.$myRequest({
					url: 'api/member/getUserInfo',
					method: 'post',
					data: {}
				});
				const tokenMobile = resGetUserInfo.mobile;
				if (tokenMobile.length !== 11) {
					uni.setStorageSync('token_mobile', "");
					uni.setStorageSync('token', '')
					uni.setStorageSync('islogin', false)
					const browserParameterStr = sessionStorage.getItem('BrowserAddressParameter')
					const browserParameter = browserParameterStr ? JSON.parse(browserParameterStr) : {}
					delete browserParameter.uid;
					delete browserParameter.u;
					sessionStorage.setItem('BrowserAddressParameter', JSON.stringify(browserParameter))
					uni.redirectTo({
						url: '/pages/index/index/?' + qs.stringify({
							...browserParameter,
							uid: undefined
						})
					})
					// #ifdef H5
					window.location.href = `/#/?${qs.stringify(browserParameter)}`
					// #endif
					return;
				}
				console.log('infoMap',infoMap)

				const res = await this.$myRequest({
					url: 'api/member/updateInfo',
					method: 'post',
					data: infoMap,
				});

				if (res.newNumber == true) {
					if (res.spePushResut.pushSuccess == true) {
						var ss = res.spePushResut.skipUrl
						if (ss) {
							uni.setStorageSync('authorize', true)
							uni.setStorageSync('authorizeUrl', ss)
						}

					}

				}
				const temp = res.spePushResut||{}
				temp.amount = this.expectAmount+20000;
				uni.setStorageSync('spePushResut', temp);
				if (temp.pushSuccess) {
					return this.$refs.protocolRef.showModal(res.spePushResut, infoMap);
				}else if(temp.orderNo){
					return this.$refs.protocolRef.submit(res.spePushResut.orderNo); 
				}else{
					uni.redirectTo({
						url: '/pages/index/result'
					})
				}
			}


		},
		components: {
			pickers,
			axbCheckBox,
			selectQuestion,
			MbuttomVue,
			mpopum,
			protocol,
			mProgress,
			userInfo
		},
	}
</script>

<style lang="scss" scoped>
.form-box{
	padding: 30rpx;
	box-sizing: border-box;
	padding-top:0;
	min-height: 100vh;
	--primary-color:#2F53EE;
	.estimate-amount-box{
		display: flex;
		justify-content: space-between;
		padding: 0 30rpx;
		align-items: center;
		.value{
			color: var(--primary-color);
			font-weight: 500;
			font-size: 60rpx;
		}
		.label{
			color: #666;
			font-size:26rpx
		}
		.right{
			color: #333;
			font-size: 28rpx;
			text{
				font-size: 50rpx;
				font-weight: 500;
			}
		}
	}
	.tips{
		text-align: center;
		color: #dd524d;
		font-size: 26rpx;
		width: 100%;
		margin-top: 30px;
		
	}

}
</style>